import json
from datetime import datetime

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect
from Strategy.models import TStrategy
import datetime

# Create your views here.

# 策略管理
from django.views import View

# 策略列表
from Django_Admin.settings import strategy_col, sim_strategy_col


class strategy(View):

    # 点击左侧栏策略管理时调用
    def get(self, request):
        request.session['s'] = 'y'
        return render(request, "strategy.html")

    def post(self, request):
        dataTable = {}
        aodata = json.loads(request.POST.get("aodata"))
        for item in aodata:
            if item['name'] == "sEcho":
                sEcho = int(item['value'])  # 客户端发送的标识
            if item['name'] == "iDisplayStart":
                iDisplayStart = int(item['value'])  # 起始索引
            if item['name'] == "iDisplayLength":
                iDisplayLength = int(item['value'])  # 每页显示的行数
        if request.POST.get('strategyId', None):
            # 如果是搜索，从mysql查出数据并排序，模糊查询
            strategy_list = TStrategy.objects.values().order_by("-CreateTime").filter(
                StgName__contains=request.POST.get("strategyId"))
            # modify by zx 按照策略创建时间倒序排序
            # print(strategy_list)
            # userList = all_strategy.find({'StgName': {"$regex": request.POST.get('strategyId') + ".*"}}).sort(
            #     'FirstTime', -1)
        else:
            # 如果是一开始的加载list页面，直接从mysql中群查，把所有数据渲染前台
            strategy_list = TStrategy.objects.values().order_by("-CreateTime")
            # userList = all_strategy.find().sort('FirstTime', -1)
        resList = list(strategy_list)
        resultLength = len(resList)
        paginator = Paginator(resList, iDisplayLength)
        # warning_list是一个page对象<Page 1 of 1>
        # 把商品分成 10 个一页。
        try:
            warning_list = paginator.page(iDisplayStart / 10 + 1)
        # 请求页数错误
        except PageNotAnInteger:
            warning_list = paginator.page(1)
        except EmptyPage:
            warning_list = paginator.page(paginator.num_pages)
        data = []
        for item in warning_list:
            # 到paper_approval表中查询指定stgid对应的仿真审批信息，并返回去重后的status
            # Sim_approval_status = TPaperApproval.objects.order_by(
            #     'UpdateTime').filter(StgID=item['StgID']).values("Status")
            # Sim_approval_status = list(Sim_approval_status)
            # Sim_approval_status = Sim_approval_status[0]["Status"] if Sim_approval_status else ''
            Sim_approval_status = ''
            row = {
                "StrategyID": item['StgID'],
                "StrategyName": item['StgName'],
                "CreateDateTime": str(item['CreateTime']).split('.')[0],
                "LatestBackTestDateTime": str(item['BackUpdateTime']).split('.')[0],
                "LatestSimDateTime": str(item.get('SimUpdateTime', '')),
                "BackTestCount": item['BackTest'],
                "SimCount": item['Sim'],
                "Status": str(item['Status']),
                'sim_approval_status': Sim_approval_status,
                'option': ''
            }
            data.append(row)

        dataTable['iTotalRecords'] = resultLength  # 数据总条数
        dataTable['sEcho'] = sEcho + 1
        dataTable['iTotalDisplayRecords'] = resultLength  # 显示的条数
        dataTable['aaData'] = data
        return JsonResponse(dataTable, safe=False)


# 新增策略，自动生成strategy_id,int类型自增1
def get_strategy_id(request):
    # 先从数据库中查询策略，按策略Id倒序排序，取第一个值，然后自增1即为strategy_id的值
    a_list = TStrategy.objects.values("StgID").order_by("-StgID")
    a_list = list(a_list)
    stgid = a_list[0].get("StgID")
    stgid += 1
    return HttpResponse(stgid)


#######################待完善###########
def back_strategy_insert(request):
    StgID = request.POST['StgID']
    StgName = request.POST['StgName']

    # the_time = datetime.now()
    TStrategy.objects.create(
        StgID=StgID,
        StgName=StgName,
        StgType=2,
        CreateTime=datetime.datetime.now(),
        BackTest=0,
        Sim=0,
        Status=1,
        CustomerID=12345
    )

    return HttpResponse('')




